﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace PoJun.Tools.Http
{
    #region IP操作

    /// <summary>
    /// IP操作
    /// </summary>
    public class IP
    {
        #region 取用户的真实IP地址

        /// <summary>   
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址   
        /// </summary>   
        public static string GetRealIPAddress()
        {
            string result = String.Empty;
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (result != null && result != String.Empty)
            {
                //可能有代理   
                if (result.IndexOf(".") == -1)    //没有"."肯定是非IPv4格式   
                    result = null;
                else
                {
                    if (result.IndexOf(",") != -1)
                    {
                        //有","，估计多个代理。取第一个不是内网的IP。   
                        result = result.Replace(" ", "").Replace("'", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIPAddress(temparyip[i])
                                && temparyip[i].Substring(0, 3) != "10."
                                && temparyip[i].Substring(0, 7) != "192.168"
                                && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                return temparyip[i];    //找到不是内网的地址   
                            }
                        }
                    }
                    else if (IsIPAddress(result)) //代理即是IP格式   
                        return result;
                    else
                        result = null;    //代理中的内容 非IP，取IP   
                }
            }
            string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (null == result || result == String.Empty)
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (result == null || result == String.Empty)
                result = HttpContext.Current.Request.UserHostAddress;
            return result;
        }

        #endregion

        #region 判断是否是IP地址格式 0.0.0.0  

        /// <summary>  
        /// 判断是否是IP地址格式 0.0.0.0  
        /// </summary>  
        /// <param name="str1">待判断的IP地址</param>  
        /// <returns>true or false</returns>  
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }

        #endregion

        #region 获取客户端IP

        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            string userIP;
            // HttpRequest Request = HttpContext.Current.Request;
            HttpRequest Request = HttpContext.Current.Request; // ForumContext.Current.Context.Request;
            // 如果使用代理，获取真实IP
            if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                userIP = Request.ServerVariables["REMOTE_ADDR"];
            else
                userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (userIP == null || userIP == "")
                userIP = Request.UserHostAddress;
            return userIP;
        }

        #endregion

        #region 将一个IP字符串转为Long型

        /// <summary>
        /// 将一个IP字符串转为Long型
        /// </summary>
        /// <param name="ip">ip</param>
        /// <returns></returns>
        public static long IPConvertLong(string ip)
        {
            //从大到小排列ip,与IPAddress不同
            if (string.IsNullOrEmpty(ip) || ip == "::1")
            {
                return 0;
            }
            string[] ipsegmentArray = ip.Split('.');
            if (ipsegmentArray.Length != 4)
            {
                ipsegmentArray = "127.0.0.1".Split();
            }
            long ip1 = int.Parse(ipsegmentArray[0]);
            int ip2 = int.Parse(ipsegmentArray[1]);
            int ip3 = int.Parse(ipsegmentArray[2]);
            int ip4 = int.Parse(ipsegmentArray[3]);
            long ip0 = (ip1 << 24) + (ip2 << 16) + (ip3 << 8) + ip4;
            return ip0;
        }

        #endregion

        #region 将一个Long型的ip转成字符串

        /// <summary>
        /// 将一个Long型的ip转成字符串
        /// </summary>
        /// <returns></returns>
        public static string LongConvertIP(long ip)
        {
            long ip1 = ip >> 24 & 0xFF;
            long ip2 = ip >> 16 & 0xFF;
            long ip3 = ip >> 8 & 0xFF;
            long ip4 = ip & 0xFF;
            var ipstr = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
            return ipstr;
        }

        #endregion 
    }

    #endregion
}
